﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Text;
using System.Text.RegularExpressions;

namespace Stanza.MSBuild.Tasks
{
    public class ProjectFileHandler : FileHandler
    {
        public ProjectFileHandler( PublishInfo pubInfo )
            : base( pubInfo )
        {
        }

        public override void ParseFile( string fileName )
        {
            string projectPath = Path.GetDirectoryName( fileName );

            Info.AddPublishFile( new PublishFile { FileName = fileName, ModifyFile = UpdateProjectFile } );

            XDocument xmlDoc = ReadSourceFileXml( fileName );
            XmlNamespaceManager nsMgr = new XmlNamespaceManager( xmlDoc.CreateNavigator().NameTable );
            nsMgr.AddNamespace( "p", FileHandler.MSBuildNamespace );

            var q1 = from x in xmlDoc.XPathSelectElements( "//p:ItemGroup", nsMgr ) select x;
            foreach( XElement itemGroup in q1.AsEnumerable() )
            {
                var q2 = from x in itemGroup.XPathSelectElements( "p:Compile | p:Content | p:None  | p:Resource | p:Page | p:ApplicationDefinition", nsMgr ) select x;
                foreach( XElement fileInclude in q2.AsEnumerable() )
                {
                    string projectFile = fileInclude.Attribute( "Include" ).Value;
                    string projectFullName = Path.Combine( projectPath, projectFile );
                    Info.AddPublishFile( new PublishFile { FileName = projectFullName } );
                }
            }
        }

        private Stream UpdateProjectFile( Stream readStream )
        {
            XDocument xmlDoc = ReadSourceFileXml( readStream );
            XmlNamespaceManager nsMgr = new XmlNamespaceManager( xmlDoc.CreateNavigator().NameTable );
            nsMgr.AddNamespace( "p", FileHandler.MSBuildNamespace );

            // Remove Team Foundation Server settings:
            //
            //    <SccProjectName>SAK</SccProjectName>
            //    <SccLocalPath>SAK</SccLocalPath>
            //    <SccAuxPath>SAK</SccAuxPath>
            //    <SccProvider>SAK</SccProvider>
            //
            ClearNode( xmlDoc, nsMgr, "SccProjectName" );
            ClearNode( xmlDoc, nsMgr, "SccLocalPath" );
            ClearNode( xmlDoc, nsMgr, "SccAuxPath" );
            ClearNode( xmlDoc, nsMgr, "SccProvider" );

            return SaveSourceFileXml( xmlDoc );
        }

        private void ClearNode( XDocument xmlDoc, XmlNamespaceManager nsMgr, string nodeName )
        {
            XElement xe = xmlDoc.XPathSelectElement( String.Concat( "//p:", nodeName ), nsMgr );
            if( xe != null )
                xe.SetValue( String.Empty );
        }
    }
}
